package com.ljx.recruitment.interview.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.recruitment.common.domain.vo.resp.PageResp;
import com.ljx.recruitment.common.exception.ApiException;
import com.ljx.recruitment.interview.constant.JobConstant;
import com.ljx.recruitment.interview.domain.dto.ResumeItmDto;
import com.ljx.recruitment.interview.domain.entity.ResumeItem;
import com.ljx.recruitment.interview.domain.vo.req.ResumeSubmitReq;
import com.ljx.recruitment.interview.domain.vo.req.ResumePageReq;
import com.ljx.recruitment.interview.domain.vo.resp.ResumeResp;
import com.ljx.recruitment.interview.enums.ResumeItemTypeEnum;
import com.ljx.recruitment.interview.enums.ResumeItemTypeRadioOptEnum;
import com.ljx.recruitment.interview.mapper.ResumeMapper;
import com.ljx.recruitment.interview.service.ResumeService;
import com.ljx.recruitment.security.util.UserUtil;
import com.ljx.recruitment.user.domain.entity.Tenant;
import com.ljx.recruitment.user.domain.entity.User;
import com.ljx.recruitment.user.service.TenantService;
import com.ljx.recruitment.user.service.UserService;
import com.ljx.recruitment.user.typehandler.details.ResumeDetails;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-11-02  21:07
 */
@Service
public class ResumeServiceImpl extends ServiceImpl<ResumeMapper, ResumeItem> implements ResumeService {

    @Autowired
    private ResumeMapper resumeMapper;

    @Override
    public List<ResumeItmDto> init() {
        Tenant tenant = SpringUtil.getBean(TenantService.class).getById(UserUtil.tryToGetTenantId());
        List<ResumeItmDto> resumeItems = tenant.getResumeDetails();
        fillDefaultValue(resumeItems, false);
        return resumeItems;
    }

    @Override
    public List<ResumeItmDto> refresh() {
        List<ResumeItmDto> resumeItems = resumeMapper.getList();
        fillDefaultValue(resumeItems, true);
        return resumeItems;
    }

    private void fillDefaultValue(List<ResumeItmDto> resumeItems, boolean isRefresh) {
        for (ResumeItmDto resumeItemDto : resumeItems) {
            if (isRefresh) {
                resumeItemDto.setDisplay(true);
            }
            if (CollectionUtil.isNotEmpty(resumeItemDto.getChildList())){
                for (ResumeItmDto child : resumeItemDto.getChildList()) {
                    if (isRefresh) {
                        child.setDisplay(true);
                    }
                    child.setDefaultValue("");
                    if (child.getType().equals(ResumeItemTypeEnum.RADIO.getKey())){
                        child.setOpts(ResumeItemTypeRadioOptEnum.getOpts(child.getCode()));
                    }
                }
            }
        }
    }

    @Override
    public ResumeResp getInfo(Long resumeItemId) {
        ResumeItem resumeItem = resumeMapper.selectById(resumeItemId);
        return BeanUtil.copyProperties(resumeItem, ResumeResp.class);
    }

    @Override
    public ResumeResp submit(ResumeSubmitReq req) {
        ResumeItem resumeItem;
        if (Objects.isNull(req.getId())){
            checkSubmitParams(req);
            resumeItem = BeanUtil.copyProperties(req, ResumeItem.class);
            if (Objects.isNull(req.getPId())) {
                resumeItem.setPId(JobConstant.DEFAULT_RESUME_PID);
            }
            if (Objects.isNull(req.getPriority())){
                Integer count = resumeMapper.selectCount(new LambdaQueryWrapper<ResumeItem>()
                        .eq(ResumeItem::getPId, req.getPId()));
                resumeItem.setPriority(count + 1);
            }
            resumeMapper.insert(resumeItem);
        } else {
            resumeItem = resumeMapper.selectById(req.getId());
            BeanUtils.copyProperties(req, resumeItem);
            resumeMapper.updateById(resumeItem);
        }
        return getInfo(resumeItem.getId());
    }

    private void checkSubmitParams(ResumeSubmitReq req) {
        if (StrUtil.isEmpty(req.getCode()) || StrUtil.isEmpty(req.getName()) || Objects.isNull(req.getType())){
            throw new ApiException("必要参数不能为空");
        }
    }

    @Override
    public PageResp<ResumeResp> getPage(ResumePageReq req) {
        LambdaQueryWrapper<ResumeItem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(req.getKey())){
            lambdaQueryWrapper.like(ResumeItem::getName, req.getKey());
        }
        Page<ResumeItem> page = resumeMapper.selectPage(new Page<>(req.getCurrPage(), req.getPageSize()), lambdaQueryWrapper);
        return PageResp.<ResumeResp>builder()
                .list(BeanUtil.copyToList(page.getRecords(), ResumeResp.class))
                .total(page.getTotal())
                .build();
    }

    @Override
    public Object getValueByCode(ResumeDetails resumeDetails, String key) {
        for (ResumeItmDto resumeDetail : resumeDetails) {
            for (ResumeItmDto childItem : resumeDetail.getChildList()) {
                if (childItem.getCode().equals(key)){
                    return childItem.getDefaultValue();
                }
            }
        }
        return null;
    }

    @Override
    public Boolean checkRecommend(ResumeDetails resumeDetails) {
        String recommendCode = (String) getValueByCode(resumeDetails, "recommend code");
        if (StrUtil.isBlank(recommendCode)) {
            return false;
        }
        User user = SpringUtil.getBean(UserService.class).getByRecommendCode(recommendCode);
        return Objects.nonNull(user) && UserUtil.tryToGetTenantId().equals(user.getTenantId());
    }

    @Override
    public void checkResumeParams(ResumeDetails resumeDetails) {
        Map<String, Boolean> notCheckParamsMap = new HashMap<>();
        notCheckParamsMap.put("recommend code", true);
        for (ResumeItmDto resumeDetail : resumeDetails) {
            // 不展示就无需检查
            if (!resumeDetail.getDisplay()) {
                continue;
            }
            for (ResumeItmDto resumeItem : resumeDetail.getChildList()) {
                if (!resumeItem.getDisplay()) {
                    continue;
                }
                if (!notCheckParamsMap.containsKey(resumeItem.getCode()) &&
                        (Objects.isNull(resumeItem.getDefaultValue()) || StrUtil.isEmpty(resumeItem.getDefaultValue().toString()))) {
                    throw new ApiException("参数：" + resumeItem.getName() + "不能为空");
                }
            }
        }
    }
}
